package com.hmdp.utils;


import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Slf4j
@Component
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time,unit);
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public<R,ID> R queryWithLogicalExpire(String keyPrefix,String lockPrefix,ID id, Class<R> type,
                                          Function<ID,R> dbFallback, Long lockTime, TimeUnit lockUnit
                                            , Long logiacalTime, TimeUnit logicalUnit) {
        String key = keyPrefix+id;

        String json = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isBlank(json)){

            //未命中，不是热点商店直接返回null，因为这里是高并发场景
            return null;
        }
        //命中先返回对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();

        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())){
            //没过期直接返回
            return r;
        }
        //过期。重建缓存
        //获取互斥锁
        String lockKey = lockPrefix+id;
        boolean lock = tryLock(lockKey,lockTime,lockUnit);
        if (lock){
            //成功拿到锁，开个线程实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    R apply = dbFallback.apply(id);
                    Thread.sleep(100);
                    setWithLogicalExpire(keyPrefix+id, apply,logiacalTime ,logicalUnit );
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(lockKey);
                }
            });
        }
        //返回过期的商店信息
        return r;
    }

//    public<R,ID> void saveShop2Redis(String keyPrefix,ID id,Long expireSeconds,
//                                     Function<ID,R> dbFallback) throws InterruptedException {
//        R r = dbFallback.apply(id);
//        RedisData redisData = new RedisData();
//        redisData.setData(r);
//        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
//        stringRedisTemplate.opsForValue().set(keyPrefix+id, JSONUtil.toJsonStr(redisData));
//
//    }

    public<R,ID> R queryWithMutex(String keyPrefix,String lockPrefix,ID id, Class<R> type,
                                     Function<ID,R> dbFallback, Long shopTime,
                                  TimeUnit shopUnit, Long lockTime, TimeUnit lockUnit,
                                  Long nullTime, TimeUnit nullUnit) {
        String key = keyPrefix+id;

        String json = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isNotBlank(json)){

            R r = JSONUtil.toBean(json, type);
            return r;
        }

        if(json!=null){
            return null;
        }

        String lockKey = lockPrefix + id;

        R r = null;

        try {
            boolean isLock = tryLock(lockKey,lockTime,lockUnit);

            if (!isLock){
                //失败休眠后重试
                Thread.sleep(50);
                return queryWithMutex(keyPrefix,lockPrefix,id,type,
                        dbFallback,shopTime,shopUnit,lockTime,
                        lockUnit,nullTime,nullUnit);
            }

            //获取锁成功，进行doublecheck
            json = stringRedisTemplate.opsForValue().get(key);

            if (StrUtil.isNotBlank(json)){

                r = JSONUtil.toBean(json, type);
                return r;
            }

            if(json!=null){
                return null;
            }
            //doublecheck没有数据再进行查找数据库
            r = dbFallback.apply(id);
            //模拟mysql查数据需要的时间
            Thread.sleep(200);
            if (r == null){
                //设置空值防止缓存穿透
                stringRedisTemplate.opsForValue().set(key, "", nullTime,nullUnit);
                return null;
            }

            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(r),shopTime,shopUnit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(lockKey);
        }

        return r;

    }



    private boolean tryLock(String key, Long shopTime,
                            TimeUnit shopUnit){
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1",shopTime, shopUnit);
        return BooleanUtil.isTrue(aBoolean);
    }

    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    public<R,ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type,
                                        Function<ID,R> dbFallback, Long time, TimeUnit unit) {
        String key = keyPrefix+id;

        String json = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isNotBlank(json)){
            //命中，返回结果
            R r = JSONUtil.toBean(json, type);
            return r;
        }

        if(json!=null){
            //未命中，不为空，则为””空值
            return null;
        }
        // 为空值,查数据库
        R r = dbFallback.apply(id);

        if (r == null){
            //设置空值防止缓存穿透
            stringRedisTemplate.opsForValue().set(key, "", time,unit);
            return null;
        }
        //调用set方法存入缓存
        this.set(key, r, time, unit);


        return r;

    }
}
